package com.gmrz.uap.role;

import com.alibaba.druid.util.StringUtils;
import com.gmrz.uap.cfg.SystemConst;
import com.gmrz.uap.common.ControllerSupport;
import com.gmrz.uap.common.UAPSSOHelper;
import com.gmrz.uap.model.Resource;
import com.gmrz.uap.model.ResourceRole;
import com.gmrz.uap.model.Role;
import com.gmrz.uap.model.User;
import com.gmrz.uap.operlog.OperLogService;
import com.gmrz.uap.resource.ResourceInterceptor;
import com.gmrz.uap.resource.ResourceService;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.render.JsonRender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class RoleController extends ControllerSupport {

    private static final Logger LOG = LoggerFactory.getLogger(RoleController.class);

    /**
     * 角色管理主页面
     */
    @Before(ResourceInterceptor.class)
    public void index() {
    }

    /**
     * 根据前台发过来的参数进行查询，可以进行分页，排序
     */
    public void list() {

        int page = getParaToInt(SystemConst.DATATABLE_PAGINATE_OFFSET, SystemConst.DATATABLE_PAGINATE_OFFSET_DEFAULT);
        int rows = getParaToInt(SystemConst.DATATABLE_PAGINATE_LIMIT, SystemConst.DATATABLE_PAGINATE_LIMIT_DEFAULT);

        String sort = getPara(SystemConst.DATATABLE_PAGINATE_SORT, SystemConst.DEFAULT_ORDERBY_ORDERNUMBER);
        String order = getPara(SystemConst.DATATABLE_PAGINATE_ORDER, SystemConst.DATATABLE_PAGINATE_ORDER_DEFAULT);

        Role role = getModel(Role.class);

        Page<Role> descPage = RoleService.me.findRoleListForPaginate(role, page, rows, sort, order);

        result.put(SystemConst.DATATABLE_PAGINATE_TOTAL, descPage.getTotalRow());
        result.put(SystemConst.DATATABLE_PAGINATE_ROWS, descPage.getList());

        render(responseJsonRender(result));
    }

    /**
     * 增加页面跳转
     */

    public void add() {
        render("form" + SystemConst.VIEW_EXTENDSION);
    }

    /**
     * 保存数据信息
     */
    public void save() {

        Role role = getModel(Role.class);
        if (StringUtils.isEmpty(role.getDes())) {
            role.setDes("");
        }

        role.setRoleName(role.getRoleName().trim());

        if (null == role) {
            message = getRes().get("system.validator.paramnull");
            return;
        }

        List<Role> all = RoleService.me.findAll();


        List<String> rolenames = new ArrayList<String>();

        for (Role r : all) {
            rolenames.add(r.getRoleName());
        }

        if (!rolenames.contains(role.getRoleName())) {

            flag = RoleService.me.save(role);

            if (flag) {
                message = getRes().get("role.from.add.success");
            } else {
                message = getRes().get("role.form.add.failure");
            }
        } else {
            message = getRes().get("role.form.add.exist");
        }

        //增加系统操作日志
        OperLogService.me.addOperLog(getRes().get("resource.form.role.add"), role.getRoleName(), flag, message, getRequest());

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }

    /**
     * 编辑页面跳转
     */
    public void edit() {
        setAttr("role", RoleService.me.findOne(getPara()));
        render("form" + SystemConst.VIEW_EXTENDSION);
    }

    /**
     * 修改数据信息
     */
    public void update() {
        Role role = getModel(Role.class);

        if (null == role) {
            message = getRes().get("system.validator.paramnull");
            return;
        }

        flag = RoleService.me.update(role);

        if (flag) {
            message = getRes().get("role.form.update.success");
        } else {
            message = getRes().get("role.from.update.failure");
        }

        //增加系统操作日志
        OperLogService.me.addOperLog(getRes().get("resource.form.role.edit"), role.getRoleName(), flag, message, getRequest());

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }

    /**
     * 根据ID删除数据信息，可以同时删除多个，数据使用逗号(,)隔开
     */
    public void remove() {

        String ids = getPara(0);
        String role_names = getPara(1);
        boolean roleFlag = true;

        if (StrKit.isBlank(ids)) {
            message = getRes().get("system.validator.paramnull");
            return;
        }
        User user = UAPSSOHelper.getUserByUapSessionId(getRequest());
        List<Role> roles = RoleService.me.getRoleListByUserId(user.getUserId());

        String[] idArr = ids.split(SystemConst._DEFAULT_SEPARATOR_COMMA);
        List<String> idList = Arrays.asList(idArr);
        for(Role r : roles){
            String roleId = r.getRoleId();
            if(idList.contains(roleId)){
                message = "删除的角色中包含自身角色";
                roleFlag = false;
            }
        }

        if(roleFlag) {
            flag = RoleService.me.remove(ids);

            if (flag) {
                message = getRes().get("role.form.remove.success");
            } else {
                message = getRes().get("role.form.remove.failure");
            }
        }

        //增加系统操作日志
        OperLogService.me.addOperLog(getRes().get("resource.form.role.remove"), role_names, flag, message, getRequest());

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }

    /**
     * 判断角色是否存在
     */
    public void exist() {
        flag = RoleService.me.exist(getPara());
        render(responseJsonRender(flag));
    }

    public void accredit() {
        setAttr("role_id", getPara());
    }

    public void getResource() {
        String roleId = getPara("roleId");
        List<String> allResourceByRoleId = ResourceService.me.findAllResourceByRoleId(roleId);
        result.put("resource", allResourceByRoleId);
        render(responseJsonRender(result));
    }

    /**
     * 根据角色ID保存资源
     */
    public void resourceTreeNodesSave() throws RoleException {

        String ids = getPara("ids");
        String roleId = getPara("roleId");
        String checkStates = getPara("checkStates");

        String[] idArr = ids.split(SystemConst._DEFAULT_SEPARATOR_COMMA);
        String[] checkStateArr = checkStates.split(SystemConst._DEFAULT_SEPARATOR_COMMA);


        //根据角色ID删除资源关联表中的数据
        if (RoleService.me.hasResourceRole(roleId)) {
            RoleService.me.removeByRoleId(roleId);
        }

        ResourceRole resourceRole = getModel(ResourceRole.class);
       // User user = (User) getSession().getAttribute(SystemConst.SESSION_USER);
        User user = UAPSSOHelper.getUserByUapSessionId(getRequest());

        if (idArr.length > 0) {
            for (int i = 0; i < idArr.length; i++) {
                resourceRole.setUserId(user.getUserId());
                resourceRole.setRoleId(roleId);
                resourceRole.setResourceId(idArr[i]);
                resourceRole.setCheckState(checkStateArr[i]);
                try {
                    flag = RoleService.me.roleResourceSave(resourceRole);
                } catch (RoleException e) {
                    LOG.error("增加角色相关的资源信息出现异常",e);
                    render(responseJsonRender(result));
                }
            }
        }

        if (flag) {
            message = getRes().get("role.form.accredit.success");
        } else {
            message = getRes().get("role.form.accredit.failure");
        }


        Role role = RoleService.me.findOne(roleId);
        String resNames = "";
        int length = idArr.length;
        if (idArr.length > 1) {
            for (String id : idArr) {
                Resource resource = ResourceService.me.findOne(id);
                resNames += getRes().get(resource.getResourceName()) + ",";
            }
        }

        //增加系统操作日志
        OperLogService.me.addOperLog2(getRes().get("resource.form.role.accredit.save"), role.getRoleName(), resNames, flag, message, getRequest());

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }


    public void findAll() {
        render(responseJsonRender(RoleService.me.findAll()));
    }

}
